package com.wxx.message;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.wxx.bean.*;
import com.wxx.utils.IPUtil;
import com.wxx.utils.OshiUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author: wxx
 * @date: 2024-08-16 16:48
 * @description 钉钉发送消息
 */
@Slf4j
public class DingDingSender extends MessageSenderAbs {

    private String url;

    private String secret;

    @Override
    public void init(ProBean proBean) {
        super.init(proBean);
        this.url = proBean.getProperties().getProperty("dingding.url");
        this.secret = proBean.getProperties().getProperty("dingding.secret");
    }


    @Override
    public boolean sendMessage(String content) {
        log.info("content = " + content);
        try {
            DingDingText dingDingText1 = DingDingText.builder()
                    .content(content)
                    .build();
            DingDingMessageBean dingDingMessageBean = DingDingMessageBean.builder()
                    .text(dingDingText1)
                    .msgtype("text")
                    .build();
            String post = HttpUtil.post(processUrl(url), JSON.toJSONString(dingDingMessageBean));
            log.info("post:{}", post);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 对钉钉的url进行加签
     *
     * @param url
     * @return https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&timestamp=XXX&sign=XXX
     */
    private String processUrl(String url) {
        StringBuilder urlBuilder = null;
        try {
            urlBuilder = new StringBuilder(url);
            Long timestamp = System.currentTimeMillis();
            urlBuilder.append("&timestamp=" + timestamp);

            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            urlBuilder.append("&sign=" + sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("new_url:{}", urlBuilder.toString());
        return urlBuilder.toString();
    }
}
